/**
 * Created by asus on 2016/11/23.
 */
import React, { Component,PropTypes} from 'react';
import {Link} from 'react-router';
import TabBar from '../../Component/CommonComponent/TabBar'
import Split from '../CommonComponent/Split'
import Top from '../CommonComponent/Top'
import Empty from '../CommonComponent/Empty'
import Time from '../CommonComponent/Time'
import StockDesc from '../../Component/StockManage/StockDesc';
import CheckBox from '../../Component/OrderManage/CheckBox';
import IsShowEmptyImg from '../CommonComponent/IsShowEmptyImg'
import {EditShopNum,DelShopCar,SettlementShopCar,StockList,AddWarehouseOrder,ListByOrderNo,MyInfo,AddressList} from '../../Action/auth'
//import ChangeNum from '../CommonComponent/ChangeNum';
import ChangeNum from '../../Component/OrderManage/ChangeNum';
import DelayModal from '../../Component/CommonComponent/DelayModal'
import iScroll from 'iscroll/build/iscroll-probe';
import $ from 'jquery';

export default class MyStock extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            index:0,
            selectAll:false,
            toRender:1,
            amount : 0,
            stockList:[],
            mobile:'',
            name:'',
            address:'',
            addressId:this.props.location.query.area?this.props.location.query.area:'',
            modalDelay:false,
            shipNum:0,
            nowNum:0,
            grade:0,
            addressList:[],
            display:'block',
            items: [],
            pullDownStatus: 3,
            pullUpStatus: 0,
            scrollTop:0,
            loadMore:false,
            end:false,
            last:false,
        };
        this.isUseSelectAll = false;
        this.amount = 0;
        this.select = [];
        this.selectNum = [];
        this.selectDel = [];
        this.selectStock = [];
        this.click = true;
        this.page = 1;
        this.over = false;
        this.dataList=[];
        this.itemsChanged = false;
    }

    static contextTypes = {
        router:PropTypes.object
    }

    async componentWillMount() {
        await this.getMyInfo();
        await this.getStockList(1);
        await this.getAddressList();
        this.getAddress();
        if(this.state.grade==1){
            this.setState({shipNum:5,nowNum:5})
        }else if(this.state.grade==2){
            this.setState({shipNum:20,nowNum:20})
        }else if(this.state.grade==3){
            this.setState({shipNum:40,nowNum:40})
        }else if(this.state.grade==4){
            this.setState({shipNum:50,nowNum:50})
        }else if(this.state.grade==5){
            this.setState({shipNum:60,nowNum:60})
        }else if(this.state.grade==6){
            this.setState({shipNum:80,nowNum:80})
        }
    }

    async getMyInfo(){
        await MyInfo()
            .then(res=>{
                this.setState({grade:res.AGENT_GRADE})
            })
    }

    async getStockList(page){
        if(this.over){
            return
        }
        this.setState({display:'block',loadMore:true})
        await StockList(page)
            .then(res=>{
                this.setState({loadMore:false});
                if(this.page==Math.ceil(res.total/res.pageSize)){
                    this.over=true;
                }else{
                    this.over=false;
                }
                this.dataList = this.dataList.concat(res.resultList);
                this.setState({stockList:this.dataList,display:'none'});
                this.page++;
            })
            .catch(err=>{
                console.warn('err',err)
            })
    }

    end(){
        let h = Math.floor(parseFloat($('#scrollWrap').height()));
        let wrapH = Math.ceil(parseFloat($('#listWrap').height()));
        if( (h - wrapH-5)<=$('#listWrap').scrollTop() ){
            if(this.over){
                this.setState({loadMore:false,end:true});
            }else{
                this.setState({loadMore:true});
                this.getStockList(this.page)
            }
        }
    }

    //获取地址列表
    async getAddressList(){
        await AddressList()
            .then(res=>{
                this.setState({addressList:res.resultList})
            })
            .catch(err=>{
                console.warn('获取地址列表错误',err)
            })
    }

    async getAddress(){
        //从地址里面选择的
        if(this.props.location.query.getAdd){
            const address = this.props.location.query.address;
            const detail = this.props.location.query.detail;
            this.setState({address:address+detail})
        //默认选择第一个
        }else{
            if(this.state.addressList.length != 0){
                this.setState({
                    address:this.state.addressList[0].address + this.state.addressList[0].detail,
                    addressId:this.state.addressList[0].id
                })
            }
        }
    }

    //全选/反选
    async onChangeState(){
        this.isUseSelectAll = true
        this.setState({selectAll:!this.state.checked});
        if(this.select.length<this.state.stockList.length){
            this.select = [];
            await this.setState({selectAll:true})
            this.state.stockList.map(el=>{
                this.select.push(el.ID)
                if(this.state.grade==6){
                    this.selectNum[el.ID]=parseInt($('#'+el.ID).val())*(el.EXTRA_MSG9);
                }else{
                    this.selectNum[el.ID]=$('#'+el.ID).val();
                }
            })
        }else{
            this.setState({selectAll:false})
            this.select = [];
        }

        this.countAmount()
        this.setState({toRender:1})
        console.log('selected',this.select)
    }

    //单选
    getSelect(state,id,productImg,productName,price){
        this.isUseSelectAll = false
        console.log('state',state)
        if(state){
            this.select.push(id)
            if(this.state.grade==6){
                this.selectNum[id]=parseInt($('#'+id).val())*price;
            }else{
                this.selectNum[id]=$('#'+id).val();
            }
        }else{
            this.select = this.select.filter(el=>{
                if(el==id){
                    return false
                }
                return true
            })
        }
        this.countAmount()
        this.setState({toRender:1})
    }

    async editShopNum(id,stock,price){
        if(this.state.grade==6){
            if(parseInt($('#'+id).val())*price>stock){
                $('#'+id).val(Math.floor(parseInt(stock)/price));
                this.selectNum[id]=parseInt($('#'+id).val())*price;
                this.countAmount()
            }else if($('#'+id).val()>0 && parseInt($('#'+id).val())*price<=stock){
                this.selectNum[id]=parseInt($('#'+id).val())*price;
                this.countAmount()
            }else{
                $('#'+id).val(1)
                this.selectNum[id]=parseInt($('#'+id).val())*price;
                this.countAmount()
            }
        }else{
            if($('#'+id).val()>stock){
                $('#'+id).val(stock);
                this.selectNum[id]=$('#'+id).val();
                this.countAmount()
            }else if($('#'+id).val()>0 && $('#'+id).val()<=stock){
                this.selectNum[id]=$('#'+id).val();
                this.countAmount()
            }else{
                $('#'+id).val(1)
                this.selectNum[id]=$('#'+id).val();
                this.countAmount()
            }
        }

    }

    reduce(id,stock,price){
        let num = $('#'+id).val()
        if(num>1){
            $('#'+id).val(num-1);
            this.selectNum[id]=parseInt($('#'+id).val())*price;
            this.countAmount()
        }else{
            $('#'+id).val(1)
            this.selectNum[id]=parseInt($('#'+id).val())*price;
            this.countAmount()
        }
    }

    add(id,stock,price){
        let num = parseInt($('#'+id).val());
        if(num<Math.floor(parseInt(stock)/price)){
            $('#'+id).val(num+1);
            this.selectNum[id]=parseInt($('#'+id).val())*price;
            this.countAmount()
        }else{
            $('#'+id).val(Math.floor(parseInt(stock)/price))
            this.selectNum[id]=parseInt($('#'+id).val())*price;
            this.countAmount()
        }
    }

    //选中取货
    countAmount() {
        this.selectStock=[];
        let postNum = 0;
        this.state.stockList.map(el=>{
            let num = this.selectNum[el.ID]?this.selectNum[el.ID]:0;
            this.select.map(item=>{
                if(el.ID == item){
                    postNum += parseInt(this.selectNum[item]);
                    this.selectStock.push({productId:el.ID,num:this.selectNum[item],productName:el.NAME,productImg:el.IMAGE})
                }
            })
            console.log(this.selectStock)
        })
        let lastPostNum=0;
        if(this.state.grade==6){
            lastPostNum = (this.state.shipNum-postNum>0)? this.state.shipNum-postNum :0;
        }else{
            lastPostNum = (this.state.shipNum-postNum>0)? this.state.shipNum-postNum :0;
        }

        this.setState({amount:this.amount,nowNum:lastPostNum})
        this.amount = 0
    }

    async toSubmit(){
        if(this.click){
            this.click = false;
            if(this.select.length>0){
                let pickUpString = "";
                this.selectStock.map(item=>{
                    pickUpString += " " + item.productName;
                    pickUpString += (",数量 " + item.num + "件"+"\n");
                })
                if(confirm("确认配货" +"\n" + pickUpString + "?")){
                    if(this.state.addressId!=''){
                        await this.setState({modalDelay:true})
                        if(this.state.nowNum>0){//判断是否包邮
                            if(confirm('当前配货数量需要自己支付邮费，是否继续')){//不包邮是否继续    '上级包邮''下级自付'
                                await AddWarehouseOrder(JSON.stringify(this.selectStock),this.state.addressId,'下级自付')
                                    .then(res=>{
                                        console.log(res);
                                        alert('取货申请提交')
                                        this.click = true;
                                        this.context.router.push({pathname:'/personalCenter'})
                                        this.setState({modalDelay:false})
                                    })
                                    .catch(err=>{
                                        alert('库存不足，去进货')
                                        this.click = true;
                                        this.context.router.push({pathname:'/purchase'})
                                        this.setState({modalDelay:false})
                                        console.warn('err',err)
                                    })
                            }else{
                                this.click = true;
                                await this.setState({modalDelay:false})
                            }
                        }else{//包邮
                            await AddWarehouseOrder(JSON.stringify(this.selectStock),this.state.addressId,'上级包邮')
                                .then(res=>{
                                    console.log(res);
                                    alert('取货申请提交')
                                    this.click = true;
                                    this.context.router.push({pathname:'/personalCenter'})
                                    this.setState({modalDelay:false})
                                })
                                .catch(err=>{
                                    alert('库存不足，去进货')
                                    this.click = true;
                                    this.context.router.push({pathname:'/purchase'})
                                    this.setState({modalDelay:false})
                                    console.warn('err',err)
                                })
                        }
                    }else{
                        alert('请选择地址');
                        this.click = true;
                    }
                }else{
                    this.click = true;
                    return;
                }

            }else{
                alert('请选择商品');
                this.click = true;
            }
        }
    }

    render(){
        const {stockList,address,mobile,name,nowNum,shipNum,grade,scrollTop, loadMore,end,last}=this.state;
        return(
            <div>
                <Top
                    title ={'我的库存'}
                />
                <Split />
                <div style={{top:50,bottom:110}} className="containerNav">
                    <div id="listWrap"
                         onTouchEnd={()=>this.end()}
                         style={{position:'absolute',top:0,left:0,right:0,bottom:0,overflowX:'auto'}}>
                        <div id="scrollWrap">
                                {
                                    stockList&&stockList.map((el,index)=>{
                                        return(
                                            <div className="padd10 border_bottom flex flex-align-center" style={{height:120}}>
                                                <CheckBox
                                                    selectAll = {this.isUseSelectAll?this.state.selectAll:null}
                                                    index={index}
                                                    onSelect = {(state)=>this.getSelect(state,el.ID,el.productImg,el.productName,el.EXTRA_MSG9)}
                                                />
                                                <div className="f14 flex-1 flex homePage">
                                                    <div className="di imgPlay mr">
                                                        <img src={el.IMAGE} alt=""/>
                                                    </div>
                                                    <div className="di flex-1 flex-v">
                                                        <div>
                                                            <span className="productShow db" style={{height:20}}>{el.NAME}</span>
                                                            {/*<span className="color9">{el.DESC}</span>*/}
                                                        </div>
                                                        <div className="flex flex-pack-justify" style={{marginTop:10}}>
                                                            <div>
                                                                {/*<div>
                                                                    <span className="colorff">可配库存: </span>
                                                                    <span className="colorff">{el.WAREHOUSE_STOCK}</span>
                                                                </div>*/}
                                                                <div style={{margin:'0 0 7px'}}>
                                                                    <span className="colorff">库存: </span>
                                                                    <span className="colorff">{el.STOCK}</span>
                                                                </div>
                                                                <div style={{margin:'0 0 7px'}}>
                                                                    <span className="colorff">销量: </span>
                                                                    <span className="colorff">{el.TOTAL_STOCK}</span>
                                                                </div>
                                                                {
                                                                    (sessionStorage.getItem('myAgent')==6)?
                                                                     <div className="flex-1 flex f12">
                                                                            取货：
                                                                            <div className="di border_4 cartCount tc flex" style={{width:80}}>
                                                                                <span className="flex flex-align-center flex-pack-center"
                                                                                      style={{width:15,borderRight:'1px solid #e5e5e5'}}
                                                                                      onClick={()=>this.reduce(el.ID,el.STOCK,el.EXTRA_MSG9)}
                                                                                >-</span>
                                                                                <input
                                                                                    id={el.ID}
                                                                                    type="number"
                                                                                    className="di height100 borderno tc widthChange flex-1"
                                                                                    onBlur={()=>this.editShopNum(el.ID,el.STOCK,el.EXTRA_MSG9)}
                                                                                    placeholder="请输入库存"
                                                                                    defaultValue="1"
                                                                                />
                                                                                <span className="flex flex-align-center flex-pack-center"
                                                                                      style={{width:15,borderLeft:'1px solid #e5e5e5'}}
                                                                                      onClick={()=>this.add(el.ID,el.STOCK,el.EXTRA_MSG9)}
                                                                                >+</span>
                                                                            </div>
                                                                            *{el.EXTRA_MSG9}件
                                                                        </div>
                                                                        :
                                                                        <div className="flex-1 flex f14">
                                                                            取货：
                                                                            <div className="di border_4 cartCount tc flex" style={{width:80,border:'none'}}>
                                                                                <input
                                                                                    id={el.ID}
                                                                                    type="number"
                                                                                    style={{width:80,borderBottom:'1px solid #e5e5e5'}}
                                                                                    className="di height100 borderno tc widthChange"
                                                                                    onBlur={()=>this.editShopNum(el.ID,el.STOCK)}
                                                                                    placeholder="请输入库存"
                                                                                    defaultValue="1"
                                                                                />
                                                                            </div>
                                                                        </div>
                                                                }
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        )
                                    })
                                }
                            {
                                loadMore?
                                    <div className="tc mt f12 colorfa">
                                        加载更多
                                    </div>
                                    :null

                            }
                            {
                                end?
                                    <div  className="tc mt f12 colorfa" style={{paddingBottom:10}}>
                                        没有更多数据了哦
                                    </div>
                                    :null
                            }
                        </div>
                    </div>
                </div>
                <div className="width100 border_top" style={{position:'fixed',bottom:50,background:'#fff'}}>
                    <Link to='/chooseInfomation' query={{stock:true}}>
                        <div className="flex flex-pack-justify flex-align-center border_bottom" style={{padding:'5px 10px'}}>
                            <div className="flex flex-align-center">
                                    <span className="di positionImg" style={{lineHeight:0,width:18}}>
                                        <img src={require('../../Images/location.png')} alt=""/>
                                    </span>
                                <div style={{marginLeft:15}}>
                                    {
                                        (address==undefined||address==null||address=='' )?
                                            <div>
                                                <span className="color6 f14">完善收货信息</span>
                                            </div>
                                            :
                                            <div>
                                                <div className="f14 color6">{address}</div>
                                            </div>
                                    }
                                </div>
                            </div>
                                <span className="di" style={{width:9,height:16,lineHeight:0,marginLeft:10}}>
                                    <img src={require('../../Images/rightArrow.png')} alt=""/>
                                </span>
                        </div>
                    </Link>
                </div>

                <div className="pf bottomCount flex flex-align-center flex-pack-justify plr width100 bgDefault" style={{bottom:0}}>

                    <div className="flex flex-align-center">
                        <span className="di check_radius posr fl">
                            <input
                                type="checkbox" id="checkAll"
                                checked={this.select.length&&(this.select.length==this.state.stockList.length)?true:false}
                                onClick={()=>this.onChangeState()}
                                className="di isCheck"
                            />
                            <label htmlFor="checkAll"></label>
                        </span>
                        <span className="di f14 color6 ml height100 lh25">全选</span>
                    </div>
                    <div>
                        {/*<span className="f12 color9 flex-v" style={{marginRight:10}}>
                            <span>配货{shipNum}件包邮</span>
                            <span className={nowNum>0?'colorlv':'color9'}>还需{nowNum}件包邮</span>
                        </span>*/}

                        <button
                            onClick={()=>this.toSubmit()}
                            style={{background:'#fa6b5b'}}
                            className="settleAccount border_4 colorfff borderno"
                        >
                            取 货
                        </button>
                    </div>
                </div>
                {
                    this.state.modalDelay?
                        <DelayModal />
                        :null

                }
            </div>
        )
    }

}

